Page({
  data: {
		amount: 0,
		prizeList: [],
		showPopup: false,
		userStar: 4500,
		exchangeUnit: 1000,
		drawCount: 0,      // 当前抽奖次数
	},
  // 点击按钮时显示弹窗
  openPopup() {
    this.setData({ showPopup: true });
  },
  onPopupCancel() {
    this.setData({ showPopup: false });
  },
  onPopupConfirm(e) {
    const { count, cost } = e.detail;
    this.setData({
      userStar: this.data.userStar - cost,
      drawCount: this.data.drawCount + count,  // 累加抽奖次数
      showPopup: false
    });
  },
  onLoad(options) {
    const rawPrizes = [
      { name: '谢谢参与', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '10元代金券', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '会员7天', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '抽纸1包', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '咖啡券', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '100积分', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '再来一次', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '10积分', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
      { name: '周边小礼物', image: 'cloud://cloud1-8g4hfxry284035d7.636c-cloud1-8g4hfxry284035d7-1365437610/images/index/头像.jpg' },
    ];

    const shuffled = rawPrizes.sort(() => Math.random() - 0.5);
		this.setData({
      prizeList: shuffled,
      flippedFlags: new Array(shuffled.length).fill(false),
    });
		
		const amount = Number(options.amount) || 0; 
    let exchangeUnit = 0;

    if (amount === 9000) {
      exchangeUnit = 1000;
    } else if (amount === 900) {
      exchangeUnit = 100;
    }

    this.setData({
      amount,
      exchangeUnit
    });
  },

	handleClick(e) {
		const index = Number(e.currentTarget.dataset.index);
	
		if (this.data.drawCount <= 0) {
			wx.showToast({ title: '抽奖次数不足', icon: 'none' });
			return;
		}
	
		if (this.data.flippedFlags[index]) return;
	
		const flags = [...this.data.flippedFlags];
		flags[index] = true;
	
		this.setData({
			flippedFlags: flags,
			drawCount: this.data.drawCount - 1
		});
	
		const prize = this.data.prizeList[index];
		wx.showModal({
			title: '抽奖结果',
			content: `你抽中了：${prize.name}`,
			showCancel: false
		});
	}	
});
